package com.whynot.frame.basic.mybatis.util;



import com.whynot.frame.basic.mybatis.conroller.model.Node;
import com.whynot.frame.basic.mybatis.conroller.model.TreeNodes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描    述:树工具
 * 创建时间: 2018/07/21
 */
public class TreeUtil {

    /**
     * 遍历树形，组装成树形
     * @param list
     * @param isSync
     * @return
     */
    public static List<TreeNodes> buildNodes(List<Node> list, boolean isSync){
        List<TreeNodes> treeList=null;
        if(list!=null){
            treeList=new ArrayList<>();
            for(Node node:list){
                TreeNodes tmp=new TreeNodes(node.getId(),node.getParentId(), node.getName(),getAttrMap(node));
                treeList.add(tmp);
            }
            treeList = formartTree(treeList);
            if(treeList!=null && treeList.size()>0 && isSync){
                treeList.get(0).setOpen(true);//默认展开
            }
        }
        return treeList;
    }

    /**
     * 将结果列表记录格式化成树型结构
     * @param list
     * @return
     */
    public static List<TreeNodes> formartTree(List<TreeNodes> list) {
        List nodeList = new ArrayList<>();
        if (list != null) {
            for (TreeNodes node1 : list) {
                boolean mark = false;
                for (TreeNodes node2 : list) {
                    if (node1 != null && node1.getParentId() !=null && node1.getParentId().equals(node2.getId())) {
                        mark = true;
                        if (node2.getChildren() == null) {
                            node2.setChildren(new ArrayList());
                            node2.setOpen(false);
                            node2.setParent(false);
                        }
                        node2.getChildren().add(node1);
                        break;
                    }
                }
                if (!mark) {
                    nodeList.add(node1);
                }
            }
        }
        return nodeList;
    }

    /**
     * 得到树节点属性
     * @param node
     * @return
     */
    public static Map<String,Object> getAttrMap(Node node){
        Map<String,Object> attrs=new HashMap<>();
        attrs.put("rootId", node.getRootId());
        attrs.put("enabled", node.getIsEnable());
        attrs.put("level",node.getLevel());
        attrs.put("level",node.getLevel());
        return attrs;
    }
}